<?php

namespace WenRuns\Laravel\Http\Middleware;

use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use WenRuns\Laravel\Admin\Form\Field\Grid\Grid;

class GridForm
{
    protected $middlewarePrefix = 'admin.grid.form:';

    public function handle(Request $request, \Closure $next)
    {
        $md5String = $request->input('__form_gird_id__');
        if ($md5String && function_exists('\Opis\Closure\unserialize')) {
            $cacheIndex = 'wenruns.grid.form.' . $md5String;
            if (Cache::has($cacheIndex)) {
                $content = Cache::get($cacheIndex);
                $closure = $content['closure'] ?? null;
                if (!empty($closure)) {
                    $resp = $next($request);
                    if ($resp instanceof JsonResponse) {
                        $resp = $resp->getContent();
                    }
                    if (is_string($resp)) {
                        $resp = json_decode($resp, true);
                    }
                    $closure = \Opis\Closure\unserialize($closure);
                    $column = $content['column'];
                    $grid = new Grid($column, [$closure, '']);
                    call_user_func($closure, $grid);
                    $resp['list'] = $grid->default($resp['list'] ?? [])->initOption(2);
                    return \Illuminate\Support\Facades\Response::json($resp);
                }
            }

        }

        if (in_array($request->input('__type__'), ['__MODAL__', '__EXPAND__'])) {
            /** @var Response $resp */
            $resp = $next($request);
            $content = $resp->getOriginalContent();
            if ($content instanceof Form) {
                $scripts = [];
                /** @var Collection $tabs */
                $tabs = $content->getTab()->getTabs();
                if ($tabs->filter(function ($vo) {
                    return !empty($vo['fields'] ?? null);
                })->isNotEmpty()) {
                    $tabs->each(function ($tab, $index) use (&$scripts) {
                        /** @var Collection $fields */
                        $fields = $tab['fields'] ?? null;
                        if ($fields && $fields->isNotEmpty()) {
                            $fields->each(function ($field, $dex) use (&$scripts) {
                                $scripts[] = $field->getScript();
                            });
                        }
                    });
                } else {
                    /** @var Form\Layout\Layout $layout */
                    $layout = $content->getLayout();
                    /** @var Collection $columns */
                    $layout->columns()->each(function ($column, $index) use (&$scripts) {
                        /** @var  Form\Layout\Column $column */
                        $column->fields()->each(function ($field, $dex) use (&$scripts) {
                            $scripts[] = $field->getScript();
                        });
                    });
                }
                $scripts = array_merge($scripts, $content->script());
                $resp->header('form-scripts', json_encode($scripts));
            } else {
            }
            return $resp;
        }

        return $next($request);
    }
}
